using System.Security.Claims;

namespace EFCoreEnterpriseDemo.Services
{
    public class DataPermissionService : IDataPermissionService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public DataPermissionService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public int? GetCurrentTenantId()
        {
            var tenantId = _httpContextAccessor.HttpContext?.User?.FindFirst("TenantId")?.Value;
            return tenantId != null ? int.Parse(tenantId) : null;
        }

        public int? GetCurrentDepartmentId()
        {
            var departmentId = _httpContextAccessor.HttpContext?.User?.FindFirst("DepartmentId")?.Value;
            return departmentId != null ? int.Parse(departmentId) : null;
        }

        public List<int?>? GetAllowedDepartments()
        {
            var roles = _httpContextAccessor.HttpContext?.User?.FindAll(ClaimTypes.Role)
                ?.Select(c => c.Value)?.ToList();

            // 管理员拥有全部权限
            if (roles?.Contains("Admin") == true)
                return null;

            var currentDept = GetCurrentDepartmentId();
            if (!currentDept.HasValue)
                return new List<int?>();

            // 获取当前部门及子部门
            return new List<int?> { currentDept };
        }

        public bool CanAccess(int userId, int departmentId, int? tenantId)
        {
            var currentTenantId = GetCurrentTenantId();
            if (currentTenantId != tenantId)
                return false;

            var allowedDepartments = GetAllowedDepartments();
            return allowedDepartments == null || allowedDepartments.Contains(departmentId);
        }
    }
}